package com.jhc.drone.communication.processor;


import com.jhc.drone.communication.enums.ProtocolEnum;
import com.jhc.drone.communication.network.cache.DroneCache;
import com.jhc.drone.communication.network.tcp.TcpResponseSender;
import com.jhc.drone.communication.network.udp.UdpResponseSender;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author lcp
 * @date 2025年01月2025/1/7 10:07
 * @describe
 */
@Slf4j
public class PackMessageProcessor implements MessageProcessor {

    private final ProtocolEnum protocol;

    public PackMessageProcessor(ProtocolEnum protocol) {
        this.protocol = protocol;
    }

    @Override
    public byte[] pack(Object data) {
        log.info("Packing data");
        return new byte[0];
    }

    @Override
    public void unpack(ByteBuf data, Channel channel) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void send(byte[] data, String sn) {
        //log.info("sending ....{}", sn);
        DroneCache.SERIAL_NUMBER_MAP.forEach((k, v) -> {
            if (Objects.equals(v, sn)) {
                try {
                    switch (protocol) {
                        case UDP:
                            UdpResponseSender.sendResponse(data, k);
                            break;
                        case TCP:
                            TcpResponseSender.sendResponse(data, k);
                            break;
                        case MQTT:
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    log.error("send fail channel is closed", e);
                }
            }
        });
    }

    @Override
    public void sendBySysId(byte[] data, Integer sysId) {
        log.info("sendBySysId ....{}", sysId);
        DroneCache.CHANNEL_MAP.forEach((k, v) -> {
            if (Objects.equals(k, sysId)) {
                try {
                    switch (protocol) {
                        case UDP:
                            UdpResponseSender.sendResponse(data, v);
                            break;
                        case TCP:
                            TcpResponseSender.sendResponse(data, v);
                            break;
                        case MQTT:
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    log.error("send fail channel is closed", e);
                }
            }
        });
    }

}